package it.softphone.cmc.maven;

import it.softphone.cmc.impl.ScriptletServiceClientImpl;
import it.softphone.cmc.shared.entity.Asset;
import it.softphone.cmc.shared.entity.AssetImpl;
import it.softphone.cmc.shared.entity.ScriptletAsset;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.Collections;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * 
 * Upload scriptlet mojo
 *
 */
//@MojoRequiresProject(false)
//@MojoGoal("upload")
@Mojo(	name="upload",
		requiresProject=false,
		threadSafe=true)
public class ScriptletUploadMojo extends AbstractScriptletMojo {

	//@MojoParameter(required=true,expression="${sourceDir}")
	@Parameter(required=true,property="sourceDir")
	java.io.File sourceDir;

	/**
	 * comma separated asset id
	 */
	//@MojoParameter(required=false,expression="${includes}", description="comma separated asset id")
	@Parameter(required=false,property="includes")
	String includes;
	
	private boolean equals( String a, String b ) {
		getLog().debug( String.format( "equals [%s] to [%s]", a, b) );
	
		boolean a_null_or_empty = (a == null||a.isEmpty());
		boolean b_null_or_empty = (b == null||b.isEmpty());
		
		if( a_null_or_empty  && b_null_or_empty )	return true;		
		if( a_null_or_empty  && !b_null_or_empty )	return false;
		if( !a_null_or_empty && b_null_or_empty )	return false;
		return a.equals(b);
	}
	
	private boolean acceptAsset( Asset asset, java.util.List<Asset> includeAssetList ) {
		if( asset == null ) return false;
		
		if( includeAssetList.isEmpty() ) return true;
		
		for( Asset a : includeAssetList ) {
			getLog().debug( String.format( "compare [%s] to [%s]", a, asset) );
			
			if( !"*".equals(a.getArtifactId()) && !equals(a.getArtifactId(),asset.getArtifactId()) ) continue;
			if( !equals( a.getGroupId(), asset.getGroupId())) continue;
			if( !equals( a.getVersion(), asset.getVersion())) continue;
			
			getLog().debug( "TRUE" );
			return true;
		}
		
		getLog().debug( "FALSE" );
		return false;
	}
	private void processGroupId( ScriptletServiceClientImpl service, java.io.File groupId_folder, java.util.List<Asset> includeAssetList )  {
		
		final Asset asset = service.makeAsset();
		
		if( !NOGROUPID.equals(groupId_folder.getName()) )
			asset.setGroupId( groupId_folder.getName() );
		
		File [] artifactId_files = groupId_folder.listFiles( new FilenameFilter() {

			@Override
			public boolean accept(File f, String name) {

				return name.endsWith(".js");
			}
			
		});
		
		for( File artifactId_file : artifactId_files ) {
			
			final String name = artifactId_file.getName();
			
			asset.setArtifactId(name.substring(0, name.length()-3 ) ); // remove extension 
			
			if( acceptAsset(asset,includeAssetList) ) {

				ScriptletAsset s = null;
				try {
					final String type = "";
					
					s = service.makeAssetFromFile(asset, type, artifactId_file);
					
				} catch (Exception e) {
					getLog().warn( String.format("error loading asset [%s]", asset), e);
				}		

				if( s != null ) {
					System.out.printf( String.format("try to upload asset [%s] ..... ",  asset) );
				
					service.saveScriptlet(s);
					
					System.out.println(" OK");
				}
			}
		}

	}
	
	private  java.io.File checkFolder( java.io.File folder ) throws MojoExecutionException
	{
		if( folder == null ) throw new IllegalArgumentException("folder is null!");
		
		if( !folder.exists() ) {
			final String msg = String.format("folder [%s] doesn't exist!", folder );
			getLog().error(msg);
			throw new MojoExecutionException(msg);
		}

		if( !folder.isDirectory() ) {		
			final String msg = String.format("parameter [%s] is not a folder", folder);
			getLog().error(msg);
			throw new MojoExecutionException(msg);
		}

		return folder;
	}
	
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {

		checkFolder(sourceDir); // PRE CONDITION
		
		java.io.File[] groupId_folders = sourceDir.listFiles( new FileFilter() {

			@Override
			public boolean accept(File f) {
				return f.isDirectory() && !f.isHidden() && f.canRead();
			}
			
		});
		
		java.util.List<Asset> includeAssetList = null;
		
		if ( includes == null ) {
			
			includeAssetList = Collections.emptyList();
			
		}
		else {
			
			String [] ids = includes.split(",");
			
			includeAssetList = new java.util.ArrayList<Asset>( ids.length );
			
			for( String id : ids ) {
				
				includeAssetList.add( AssetImpl.fromKey(id) );
			}
		}
		
		getLog().info( String.format("groupId folder detected #[%d]", groupId_folders.length));
		
		final ScriptletServiceClientImpl service = super.createService();

		System.out.println( "========================================");
		System.out.println( "> UPLOAD SCRIPTLET");		
		System.out.println();		
		System.out.printf( "> to [%s]\n", getBaseUrl() );		
		System.out.println( "========================================");

		
		for( java.io.File f : groupId_folders ) {
			
			getLog().info( String.format("process groupId [%s]", f.getName()));

			processGroupId(service, f, includeAssetList);
			
		}
		
		System.out.println( "========================================");

		

	}

}
